﻿using System;
using System.Collections;
using System.Windows.Forms;

namespace Ankh.BugNet.Extension.IssueTracker.Form
{
    public partial class IssuesListView : UserControl
    {
        public IssuesListView()
        {
            InitializeComponent();
        }

        public void BindListData(object[] dataSource)
        {
            foreach (var row in dataSource)
            {
                var issue = Issue.CovertByRow(row);

                var item = new ListViewItem(issue.Id.ToString());
                item.SubItems.Add(issue.Title);
                item.SubItems.Add(issue.Category);
                item.SubItems.Add(issue.Type);
                item.SubItems.Add(issue.Milestone);
                item.SubItems.Add(issue.Priority);
                item.SubItems.Add(issue.AssignedUser);
                item.SubItems.Add(issue.UpdatedAt.ToString("yyyy-MM-dd hh:mm:ss"));
                item.SubItems.Add(issue.CreatedAt.ToString("yyyy-MM-dd hh:mm:ss"));

                ListView.Items.Add(item);
            }
        }

        private int sortColumn;
        private void ListView_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (e.Column != sortColumn)
            {
                sortColumn = e.Column;
                ListView.Sorting = SortOrder.Descending;
            }
            else
            {
                if (ListView.Sorting == SortOrder.Descending)
                {
                    ListView.Sorting = SortOrder.Ascending;
                }
                else
                {
                    ListView.Sorting = SortOrder.Descending;
                }
            }

            ListView.Sort();

            ListView.ListViewItemSorter = new ListViewItemComparer(e.Column, ListView.Sorting);
        }
    }
    class ListViewItemComparer : IComparer
    {
        private int col;
        private SortOrder order;
        public ListViewItemComparer()
        {
            col = 0;
            order = SortOrder.Ascending;
        }
        public ListViewItemComparer(int column, SortOrder order)
        {
            col = column;
            this.order = order;
        }

        public int Compare(object x, object y)
        {
            int returnVal = -1;
            returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
            // Determine whether the sort order is descending.
            if (order == SortOrder.Descending)
            {
                returnVal *= -1;
            }
            return returnVal;
        }
    }
}
